package guij.taobao;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import org.apache.ibatis.exceptions.IbatisException;
import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;
import com.taobao.api.TaobaoApiException;
import com.taobao.api.TaobaoJsonRestClient;
import com.taobao.api.TaobaoRestClient;
import com.taobao.api.model.Item;
import com.taobao.api.model.ItemGetRequest;
import com.taobao.api.model.ItemGetResponse;
import com.taobao.api.model.ItemsGetResponse;
import com.taobao.api.model.ItemsListGetRequest;
import com.taobao.api.model.ItemsListGetResponse;
import com.taobao.api.model.ItemsOnSaleGetRequest;
import com.taobao.api.model.SellerCat;
import com.taobao.api.model.SellerCatsListGetRequest;
import com.taobao.api.model.SellerCatsListGetResponse;

public class TopInterface{

	public List<Item> getOnSaleItems(String sessionkey, int num,String cids){
		
		TaobaoRestClient client = null;
		try {
			client = getTopJsonAppClient();
			ItemsOnSaleGetRequest req = new ItemsOnSaleGetRequest();
			req.setFields("num_iid,title,price");	
			req.setPageSize(num);
			if(cids!=null){
				req.setSellerCids(cids);
			}
			ItemsGetResponse res = client.itemsOnSaleGet(req, sessionkey);
			return res.getItems();
		
		} catch (TaobaoApiException e) {
			e.printStackTrace();
		}
		return null;
	}
	public List<SellerCat> getSellerCids(String nick){
		TaobaoRestClient client = null;
		try {
			client = getTopJsonAppClient();
			SellerCatsListGetRequest req = new SellerCatsListGetRequest();
			req.setNick(nick);	
			SellerCatsListGetResponse res = client.sellerCatsListGet(req);
			return res.getSellerCats();
		
		} catch (TaobaoApiException e) {
			e.printStackTrace();
		}
		return null;
	}
	
	
	public Item getItem(String num_iid){
		
		TaobaoRestClient client = null;
		try {
			client = getTopJsonAppClient();
			ItemGetRequest req = new ItemGetRequest();
			req.setNumIid(num_iid);
			req.setFields("title,detail_url,nick,created,pic_url");
			ItemGetResponse res = client.itemGet(req);
			return res.getItem();
		} catch (TaobaoApiException e) {
			e.printStackTrace();
		}
		return null;
	}
	
	// 通过这个接口获得多个item
	public List<Item> getItems(String sessionkey,String num_iids){
		
		TaobaoRestClient client = null;
		try {
			client = getTopJsonAppClient();
			ItemsListGetRequest req = new ItemsListGetRequest();
			req.setNumIids(num_iids);
			req.setFields("title,detail_url,");	 
			ItemsListGetResponse res = client.itemsListGet(req);
			return res.getItems();
		
		} catch (TaobaoApiException e) {
			e.printStackTrace();
		}
		return null;
	}
	public boolean verifyTopResponse(String topParams, String topSession,
			String topSign) throws NoSuchAlgorithmException, IbatisException,
			UnsupportedEncodingException {
		StringBuilder result = new StringBuilder();
		MessageDigest md5 = MessageDigest.getInstance("MD5");
		result.append(APP_KEY).append(topParams).append(topSession).append(
				APP_SERCET);
		byte[] bytes = md5.digest(result.toString().getBytes("UTF-8"));
		BASE64Encoder encoder = new BASE64Encoder();
		return encoder.encode(bytes).equals(topSign);
	}
    public String ParametersName(String top_parameters){

        String nick=null; 
        Map<String, String> map= convertBase64StringtoMap(top_parameters); 
        Iterator keyValuePairs = map.entrySet().iterator(); 
        for (int i = 0; i < map.size(); i++) 
        { 
        Map.Entry entry = (Map.Entry) keyValuePairs.next(); 
        Object key = entry.getKey(); 
        Object value = entry.getValue(); 
        if(key.equals("visitor_nick")){

            nick=(String) value; 

        } 
        } 

        return nick; 

    } 
	public Map<String, String> convertBase64StringtoMap(String str) {

		if (str == null)
			return null;

		BASE64Decoder decoder = new BASE64Decoder();

		String keyvalues = null;

		try {

			keyvalues = new String(decoder.decodeBuffer(str));

		} catch (IOException e) {

			// Logger.error(str + "不是一个合法的BASE64编码字符串");
			return null;

		}

		if (keyvalues == null || keyvalues.length() == 0)

			return null;

		String[] keyvalueArray = keyvalues.split("&");

		Map<String, String> map = new HashMap<String, String>();

		for (String keyvalue : keyvalueArray) {

			String[] s = keyvalue.split("=");

			if (s == null || s.length != 2)

				return null;

			map.put(s[0], s[1]);

		}

		return map;

	}
	
	public TaobaoRestClient getTopJsonAppClient() throws TaobaoApiException{
		return new TaobaoJsonRestClient(SANDBOX_URL, APP_KEY, APP_SERCET);
	}
	
	private String APP_KEY; 
	private String APP_SERCET;
	private String SANDBOX_URL;

	public String getAPP_KEY() {
		return APP_KEY;
	}
	public void setAPP_KEY(String aPPKEY) {
		APP_KEY = aPPKEY;
	}
	public String getAPP_SERCET() {
		return APP_SERCET;
	}
	public void setAPP_SERCET(String aPPSERCET) {
		APP_SERCET = aPPSERCET;
	}
	public String getSANDBOX_URL() {
		return SANDBOX_URL;
	}
	public void setSANDBOX_URL(String sANDBOXURL) {
		SANDBOX_URL = sANDBOXURL;
	}

}

